package restClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class RESTClient
{
    private String sensorID;
    private final int DEVICE_ID = 4180;
    private final String API_KEY = "dd839171-4742-4db1-bee7-388c49a2145a";
    private final String REGISTRATION_URL = "http://uclwebservicetest.cloudapp.net/Services/device.svc/device";
    private final String DATA_URL = "http://uclwebservicetest.cloudapp.net/Services/DataLogging.svc/logData";
    private final String RESULT = "\"Success\"";

    public String getSensorID()
    {
	return sensorID;
    }

    public boolean registerSensor(String sensorName)
    {
	try
	{
	    HttpClient client = new DefaultHttpClient();
	    HttpPost post = new HttpPost(REGISTRATION_URL);

	    // add header
	    post.setHeader("Authorization", "APIKey " + API_KEY);
	    post.setHeader("Content-Type", "application/json");

	    String json = "{\"DeviceId\":" + DEVICE_ID
		    + ",\"Sensors\":[{\"Interval_measure\":\"4000"
		    + "\",\"Interval_send\":\"4000\",\"Make\":\"Engduino"
		    + "\",\"Metadata\":\"ForLater\",\"Name\":\"" + sensorName
		    + "\",\"Fault_tolerance\":60"
		    + ",\"Type\":\"temperature\"}]}";

	    System.out.println(json);

	    post.setEntity(new StringEntity(json));

	    HttpResponse response = client.execute(post);

	    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
	    {
		sensorID = response.getFirstHeader(sensorName).getValue();

		BufferedReader rd = new BufferedReader(new InputStreamReader(
			response.getEntity().getContent()));

		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null)
		{
		    result.append(line);
		}

		if (result.toString().equals(RESULT))
		    return true;
		else
		    return false;
	    }
	    else
		return false;
	}
	catch (Exception e)
	{
	    e.printStackTrace();
	    return false;
	}
    }

    public boolean sendData(String temperature)
    {
	try
	{
	    HttpClient client = new DefaultHttpClient();
	    HttpPost post = new HttpPost(DATA_URL);

	    // add header
	    post.setHeader("Authorization", "APIKey " + API_KEY);
	    post.setHeader("Content-Type", "application/octet-stream");

	    String currentTime = getTime();
	    String json = "{\"deviceId\":" + DEVICE_ID + ",\"sensorId\":"
		    + sensorID + ",\"firstTime\":\"" + currentTime
		    + "\",\"lastTime\":\"" + currentTime
		    + "\",\"data\":[{\"temperature\":" + temperature
		    + ",\"humidity\":59.00,\"time\":\"" + currentTime + "\"}]}";

	    System.out.println(json);

	    post.setEntity(new StringEntity(json));

	    HttpResponse response = client.execute(post);

	    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
	    {
		BufferedReader rd = new BufferedReader(new InputStreamReader(
			response.getEntity().getContent()));

		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null)
		{
		    result.append(line);
		}

		if (result.toString().equals(RESULT))
		    return true;
		else
		    return false;
	    }
	    else
		return false;
	}
	catch (Exception e)
	{
	    e.printStackTrace();
	    return false;
	}
    }

    private String getTime()
    {
	SimpleDateFormat dateFormat = new SimpleDateFormat(
		"dd/MM/yyyy HH:mm:ss");
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(new Date());
	calendar.add(Calendar.HOUR, -1);

	return dateFormat.format(new Date(calendar.getTimeInMillis()));
    }
}
